package com.jsits.v2x.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;

/**
 * 压缩工具类
 */
public class ZipUtil
{
    /*
     * 日志
     */
    private static final Log logger = LogFactory.getLog(ZipUtil.class);
    
    /*
     * 文件分隔符
     */
    private static final String FILE_SEPARATE = System.getProperty("file.separator");
    
    /*
     * 保存zip文件
     */
    public static void saveZipFile(String zipPath, String sourceFile)
    {
        ZipOutputStream zoStream = null;
        
        try
        {
            zoStream = new ZipOutputStream(new FileOutputStream(new File(zipPath)));
            zoStream.setEncoding("UTF-8");
            zip(zoStream, new File(sourceFile), "");
        }
        catch (FileNotFoundException e)
        {
            logger.error("saveZipFile FileNotFound", e);
        }
        finally
        {
            CloseUtils.close(zoStream);
        }
    }
    
    /*
     * 压缩文件夹
     */
    public static void zip(ZipOutputStream zoStream, File file, String base)
    {
        BufferedInputStream biStream = null;
        
        try
        {
            // 判断是否为目录
            if (file.isDirectory())
            {
                File[] fileList = file.listFiles();
                
                
                zoStream.putNextEntry(new ZipEntry(base + FILE_SEPARATE));
                base = base.length() == 0 ? "" : base + FILE_SEPARATE;
                
                for (int i = 0; i < fileList.length; i++)
                {
                    zip(zoStream, fileList[i], base + fileList[i].getName());
                }
            }
            // 压缩目录中的所有文件
            else
            {
                biStream = new BufferedInputStream(new FileInputStream(file));
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zoStream.putNextEntry(zipEntry);
                
                byte[] buf = new byte[1024];
                int len = 0;
                
                while ((len = biStream.read(buf)) != -1)
                {
                    zoStream.write(buf, 0, len);
                    zoStream.flush();
                }
            }
        }
        catch (FileNotFoundException e)
        {
            logger.error("saveZipFile FileNotFound", e);
        }
        catch (IOException e)
        {
            logger.error("saveZipFile FileNotFound", e);
        }
        finally
        {
            CloseUtils.close(biStream);
        }
    }
    
    /*
     * 压缩文件并删除源文件
     */
    public static void zipFiles(String directory, String zipFile) 
    {
		try {
        	byte[] buffer = new byte[1024];
        	ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); 
            File file = new File(directory);
            File files[] = file.listFiles(); 
            for (int i = 0; i < files.length; i++) 
            { 
                FileInputStream oFileStream = new FileInputStream(files[i]); 
                out.putNextEntry(new ZipEntry(files[i].getName()));
                int length;
                while((length = oFileStream.read(buffer)) > 0) 
                {
                    out.write(buffer, 0, length);
                }
                out.closeEntry();
                oFileStream.close();
                
                //删除文件夹中的所有文件
                files[i].delete();
            }
            out.close();
            
            //删除空文件夹
            file.delete();
        } 
		catch (Exception e) 
		{
        	logger.error("Zip files in directoy: " + directory + " failed, " + e.getMessage());
        	return;
		}
		logger.info("Zip files in directoy: " + directory + " success");
	}
    
    /*
     * 保存文件
     */
	public static void saveFile(String fileName, String fileData) 
	{
		try {
			File file = new File(fileName);
	        if (!file.exists()) 
	        {
	        	file.createNewFile();
	        }
	        FileOutputStream stream = new FileOutputStream(file);
	        stream.write(fileData.getBytes("utf-8"));
	        stream.flush();
	        stream.close();
		}
		catch (Exception e) 
		{ 
			logger.error("Save file: " + fileName + " failed");
        }
	}
}
